//
//  MainTabBar.swift
//  SinaWeibo
//
//  Created by Arvin on 15/11/8.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit

@objc protocol MainTabBarDelegate: NSObjectProtocol {
    optional func addComposeController()
}

class MainTabBar: UITabBar {
    
    var composeDelegate: MainTabBarDelegate?
    
    // MARK: 按钮点击
    @objc func didClickCompose() {
        composeDelegate?.addComposeController?()
    }

    override init(frame: CGRect) {
         super.init(frame: frame)

        addSubUI()
    }

    required init?(coder aDecoder: NSCoder) {
        // 如果有调用者通过sb/xib创建该对象, 程序就会崩溃, 不使用默认, 注释这段代码
        // fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        addSubUI()
    }
    
    private func addSubUI() {
        self.backgroundImage = UIImage(named: "tabbar_background")
        self.addSubview(plusBtn)
    }
    
    private lazy var plusBtn: UIButton = {
        let b = UIButton()
        b.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        b.setImage(UIImage(named: "tabbar_compose_icon_add"), forState:UIControlState.Normal)
        b.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        b.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        b.sizeToFit()
        b.addTarget(self, action: "didClickCompose", forControlEvents: UIControlEvents.TouchUpInside)
        return b
    }()
    
    override func layoutSubviews() {
         super.layoutSubviews()
        let subviewW = self.frame.width / 5
        let subviewH = self.frame.height
        let rect = CGRectMake(0, 0, subviewW, subviewH)
        var index:CGFloat = 0.0
        for subview in subviews {
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) == true {
                subview.frame = CGRectOffset(rect, index * subviewW, 0)
//                if index == 1 {
//                    index++
//                }
//                index++
                index++ == 1 ? index++ : index
            }
        }
        plusBtn.frame = CGRectOffset(rect, subviewW * 2, 0);
    }
}
